//
//  OYNetWorkTools.swift
//  weiboCopycat
//
//  Created by Orange Yu on 2016/12/3.
//  Copyright © 2016年 Orange Yu. All rights reserved.
//

import UIKit
import AFNetworking

enum RequestType {
    case get
    case post
}

typealias CallBack = (Any?,Error?)->()
class OYNetWorkTools: AFHTTPSessionManager {

    // 创建单例对象,并添加可以接收响应的数据类型
    static var sharedTools: OYNetWorkTools = {
        let sharedTools = OYNetWorkTools()
        sharedTools.responseSerializer.acceptableContentTypes?.insert("text/html")
        sharedTools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return sharedTools
    }()
    
    // 封装AFN请求方法
    func request(requestType:RequestType,url:String,params:Any?,callBack:@escaping CallBack) {
        if requestType == .get {
            // get 请求
            get(url, parameters: params, progress: nil, success: { (_, resposeObject) in
                callBack(resposeObject,nil)
            }, failure: { (_, error) in
                callBack(nil,error)
            })
            
        }else {
            // post 请求
            post(url, parameters: params, progress: nil, success: { (_, responseObject) in
                callBack(responseObject,nil)
            }, failure: { (_, error) in
                callBack(nil,error)
            })
        }
    }
    
}


// MARK: - 发送微博相关请求
extension OYNetWorkTools {
    
    /// 发送纯文字微博
    ///
    /// - Parameters:
    ///   - status: 微博文字内容
    ///   - callBack: 回调信息
    func postWeibo(status:String,callBack:@escaping CallBack) {
        let url = "https://api.weibo.com/2/statuses/update.json"
        let accessToken = OYUserInfoViewModel.sharedUserInfo.accessToken
        let params = [
            "access_token":accessToken,
            "status":status
        ]
        request(requestType: .post, url: url, params: params, callBack: callBack)
    }
    
    func postPictureWeibo(status:String,image:UIImage,callBack:@escaping CallBack) {
        let url = "https://upload.api.weibo.com/2/statuses/upload.json"
        let acceccToken = OYUserInfoViewModel.sharedUserInfo.accessToken
        let params = [
            "access_token":acceccToken,
            "status":status
        ]
        // 将图片转换为二进制
        let imageData = UIImagePNGRepresentation(image)!
        
        post(url, parameters: params, constructingBodyWith: { (formData) in
            
            formData.appendPart(withFileData: imageData, name: "pic", fileName: "test", mimeType: "image/jpeg")
        }, progress: nil, success: { (response, error) in
            
            callBack(response,nil)
            
        }, failure: { (response, error) in
            callBack(nil,error)
        })
    }
}


// MARK: - 获取首页数据相关请求
extension OYNetWorkTools {
    func loadHomeStatus(maxid:Int64,sinceid:Int64,callBack:@escaping CallBack) {
        let url = "https://api.weibo.com/2/statuses/friends_timeline.json"
        let accesstoken = OYUserInfoViewModel.sharedUserInfo.accessToken!
        let params:[String:Any] = [
            "access_token":accesstoken,
            "max_id":maxid,
            "since_id":sinceid
            
        ]
       
        // 由于是get请求，可以拼接参数发送请求
        let path = url + "?access_token=\(accesstoken)"
        print(path)
        
        request(requestType: .get, url: url, params: params, callBack: callBack)
    }
}

// MARK: - 获取accesstoken相关请求
extension OYNetWorkTools {
    
    // 获取用户信息的请求
    func getUserInfo(access_token: String,uid:Int64,callBack:@escaping CallBack) {
        let url = "https://api.weibo.com/2/users/show.json"
        let params: [String:Any] = [
            "access_token": access_token,
            "uid": uid
        ]
        
        request(requestType: .get, url: url, params: params, callBack: callBack)
        
    }
    
    
    // 请求accesstoken
    func getAccessToken(code:String,callBack:@escaping CallBack) {
        let url = "https://api.weibo.com/oauth2/access_token"
        let params = [
            "client_id": AppKey,
            "client_secret": AppSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": Redirect_uri
        ]
        
       request(requestType: .post, url: url, params: params, callBack: callBack)
        
    }
}
